package com.lry.basic.redis;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.ArrayList;
import java.util.List;

/**
 * @author:刘仁有
 * @desc:
 * @email:953506233@qq.com
 * @data:2019/8/6
 */
//http1.0短连接 一个请求一次socket链接
//http1.1之后长连接  一个socket链接读写多次数据
public class NioServer {
    //单线程非阻塞服务器,accept和read都实现非阻塞
    public static void main(String[] args) throws IOException, InterruptedException {
        List<SocketChannel> channels = new ArrayList<>();
        ByteBuffer buffer = ByteBuffer.allocate(1024);
        ServerSocketChannel ssc = ServerSocketChannel.open();
        ssc.bind(new InetSocketAddress(9999));
        System.out.println("server start");
        System.out.println("wait for connect");
        ssc.configureBlocking(false);
        while(true){
            SocketChannel sc = ssc.accept();
            if(sc==null){
                Thread.sleep(1000);
                System.out.println("no conn");
            }else{
                sc.configureBlocking(false);
                channels.add(sc);
                System.out.println("connect success:"+sc.getRemoteAddress());
            }
            for (SocketChannel channel:channels) {
                int total = channel.read(buffer);
                if(total!=0){
                    buffer.flip();
                    System.out.println("receive data from "+channel.getRemoteAddress()+" data is:"+new String(buffer.array()));
                }
            }
        }
    }
}
